﻿using cap01.Common.Util;
using StackExchange.Redis;

namespace cap01.Common.Redis;

/// <summary>
/// 基于Redis的轻量级的pubsub，支持广播，用于不可靠的消息通知
/// </summary>
public class RedisPubSub(string channel)
{
	readonly RedisChannel _channel = RedisChannel.Literal($"cap01.notify.{channel}");
	ISubscriber _subscriber = RedisClient.Redis.GetSubscriber();

    /// <summary>
    /// 消息发布
    /// </summary>
    public long Publish(string message)
	{
		return _subscriber.Publish(_channel, message);
	}

	/// <summary>
	/// 消息订阅
	/// </summary>
	public void Subscribe(Action<string> action)
	{
		//action 里如果抛异常， 这里不处理也会被redisclient吃掉，不影响下次收消息
		_subscriber.Subscribe(_channel, (channel, message) => { action(message); });
	}

	/// <summary>
	/// 消息订阅
	/// </summary>
	public void Subscribe<T>(Action<T> action, Func<string, T> parser)
	{
		Subscribe(message =>
		{
			var para = parser(message);
			action(para);
		});
	}
}

/// <summary>
/// Redis消息订阅类别
/// </summary>
public enum RedisNotify
{
	Notify
}